package com.link.base.base.pageupload.controller;

import com.link.base.base.common.model.Attachment;
import com.link.base.base.common.service.AttachmentService;
import com.link.base.base.pageupload.model.Chunk;
import com.link.base.base.pageupload.model.FileInfo;
import com.link.base.base.pageupload.service.ChunkService;
import com.link.base.base.pageupload.utils.FileUtils;
import com.link.base.core.basic.util.YmlConstants;
import com.link.base.user.model.CoreUser;
import com.link.core.cllog.LCLogger;
import com.link.core.util.DateUtil;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 大文件分片上传
 * @author 许博文
 * @date 2018-12-27
 */
@RestController
@RequestMapping("link/pageUploader")
public class PageUploadController {
    @Resource
    private ChunkService chunkService;

    @Resource
    private AttachmentService attachmentService;

    /**
     * DESC: 分片上传文件
     *
     * @param:
     * @return:
     * @auther: bowen.xu
     * @date: 2019-01-02 09:16
     */
    @PostMapping("/chunk")
    public Map uploadChunk(Chunk chunk) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            chunkService.upload(chunk);
            // 插入方法
            chunkService.insert(chunk);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * DESC: 上传前校验当前分片编号是否已经上传，避免重复上传
     *
     * @param:
     * @return:
     * @auther: bowen.xu
     * @date: 2019-01-02 09:16
     */
    @GetMapping("/chunk")
    public Object checkChunk(Chunk chunk, HttpServletResponse response) {
        try {
            if (chunkService.checkChunk(chunk)) {
                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            }
        } catch (Exception e) {
            LCLogger.withException(e);
        }
        return chunk;
    }

    /**
     * DESC: 分片上传结束后，合并所有分片
     *
     * @param:
     * @return:
     * @auther: bowen.xu
     * @date: 2019-01-02 09:19
     */
    @PostMapping("/mergeFile")
    public Map mergeFile(FileInfo fileInfo) {
        HashMap<String, Object> result = new HashMap<>();
        try {
            CoreUser user = UserUtil.getUser();
            String realativPath = "/web/bigfile/" + user.getId() + "/" + DateUtil.dateToStr(new Date(), "yyyyMMdd");
            String realPath = YmlConstants.getPortalShareFileDir() + realativPath;

            String filename = fileInfo.getFileName();
            String file = realPath + "/" + fileInfo.getIdentifier() + "/" + filename;
            String folder = realPath + "/" + fileInfo.getIdentifier();
            FileUtils.merge(file, folder, filename);

            //  插入信息到附件表中
            Attachment attachment = new Attachment();
            attachment.setAttachmentPath(file);
            attachment.setAttachmentSize(fileInfo.getTotalSize() + "");
            attachment.setAttachmentType(fileInfo.getType());

            Long headId = fileInfo.getHeadId();
            if (headId == null) {
                headId = Long.parseLong("noMatchId");
            }
            attachment.setHeadId(headId);
            attachment.setAttachmentName(filename);
            attachment.setAttachmentOriginal(filename);

            String moduleType = fileInfo.getModuleType();
            if (StringUtils.isNull(moduleType)) {
                throw new Exception("moduleType不能为空");
            }
            attachment.setModuleType(moduleType);
            attachment.setSource("web");
            attachmentService.insert(attachment);
            Attachment newRow = attachmentService.queryById(attachment);

            result.put("success", true);
            result.put("result", newRow);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }
}
